package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Resource
    CacheClient cacheClient;

    @Override
    public Result queryShopById(Long id) {
//        Shop shop = queryWithPassThrough(id);
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        Shop shop = queryWithMutex(id);

//        Shop shop = queryWithLogicalExpire(id);

        if (null == shop)
            return Result.fail("店铺不存在");

        return Result.ok(shop);
    }

    // 建立线程池
    private static final ExecutorService CACHE_BUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 防止缓存穿透代码
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1. 根据商品id去redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 未命中直接返回
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }

        // 命中，将json转为对象类
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 判断信息是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，返回商铺信息
            return shop;
        }
        // 过期，尝试获取互斥锁,并重建缓存
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryGetLock(lockKey);

        // 判断是否获取锁成功
        if (isLock) {
            RedisData checkRedisData = checkRedisData(key, RedisData.class);
            if (checkRedisData.getExpireTime().isAfter(LocalDateTime.now()))
                return JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            else
                // 获取互斥锁成功，开启独立线程
                CACHE_BUILD_EXECUTOR.submit(() -> {
                    try {
                        saveShop2Redis(id, 20L);
                    } catch (Exception e) {
                        throw new RuntimeException();
                    } finally {
                        unlock(lockKey);
                    }
                });
        }

        // 获取互斥锁失败,返回过期的商品信息
        return shop;
    }


    // 使用互斥锁解决缓存击穿问题
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //        1. 根据商品id去redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //        2. 存在直接返回
        if (null != shopJson && !"".equals(shopJson)) {
//            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return JSONUtil.toBean(shopJson, Shop.class);
        }
//        System.out.println(shopJson);
        if ("".equals(shopJson)) {
            return null;
        }
        String lockKey = null;

        Shop shop = null;

        try {
            // 使用互斥锁解决缓存击穿问题
            lockKey = "lock:shop:" + id;
            // 1.获取互斥锁
            boolean lock = tryGetLock(lockKey);
            // 2. 判断是否获取成功
            if (!lock) {
                // 失败
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 3. 成功，再次去redis缓存中查询数据是否存在
            Shop shopData = checkRedisData(key, Shop.class);
            // 4.如果不存在再去数据查询
            if (null != shopData)
                return shopData;

            //        3. 不存在去数据查询
            shop = getById(id);
            Thread.sleep(200);
            //        4. 判断数据库中是否有数据
            if (null == shop) {
                // 为了防止缓存击穿，将查询失败的值存入redis
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                //        5. 没有直接返回错误信息
                return null;
            }
            //        6. 存在返回数据并且将数据存入redis中
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException();
        } finally {
            // 释放互斥锁
            unlock(lockKey);
        }


        return shop;
    }

    public <T> T checkRedisData(String key, Class<T> beanClass) {
        String data = stringRedisTemplate.opsForValue().get(key);
        //        2. 存在直接返回
        if (null != data && !"".equals(data)) {
            return JSONUtil.toBean(data, beanClass);
        } else {
            return null;
        }
    }

    // 防止缓存穿透代码
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //        1. 根据商品id去redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //        2. 存在直接返回
        if (null != shopJson && !"".equals(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
//        System.out.println(shopJson);
        if ("".equals(shopJson)) {
            return null;
        }

        //        3. 不存在去数据查询
        Shop shop = query().eq("id", id).one();
        //        4. 判断数据库中是否有数据
        if (null == shop) {
            // 为了防止缓存击穿，将查询失败的值存入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //        5. 没有直接返回错误信息
            return null;
        }
        //        6. 存在返回数据并且将数据存入redis中
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (null == id)
            return Result.fail("id不能为空");
        String key = CACHE_SHOP_KEY + id;
        //    1.更新数据库
        updateById(shop);
        //    2.删除缓存
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    private boolean tryGetLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    public void saveShop2Redis(Long id, Long expireSecond) {
        // 1. 查询店铺信息
        Shop shop = getById(id);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 2. 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
        // 3. 写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


}
